package com.fengziyu.lib_recyclerview_fzy.login

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.fengziyu.lib_recyclerview_fzy.R
import com.fengziyu.lib_recyclerview_fzy.RecyclerViewActivity
import com.fengziyu.lib_recyclerview_fzy.databinding.ActivityLoginBinding
import com.fengziyu.lib_recyclerview_fzy.databinding.ActivityRecyclerViewBinding
import com.fengziyu.lib_recyclerview_fzy.mvvm.BaseActivity

@Route(path = "/recyclerview/login/LoginActivity")
class LoginActivity : BaseActivity<LoginViewModel>() {
    private lateinit var binding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initData()
        
        binding.loginBtn.setOnClickListener { 
            val num = binding.num.text.toString()
            val pwd = binding.pwd.text.toString()
            Log.d("LoginParams", "num: $num, pwd: $pwd")
            viewModel.login(num, pwd)
        }
    }

    fun initData(){
        Log.d("LoginActivity", "初始化数据观察者")
        viewModel.loginResponse.observe(this) { loginResponse ->
            Log.d("LoginActivity", "收到登录响应更新: $loginResponse")
            if (loginResponse != null && loginResponse.code == 200) {
                Log.d("LoginActivity", "登录成功")
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                // 登录成功后的处理
                val intent = Intent(this, RecyclerViewActivity::class.java)
                startActivity(intent)
            } else {
                Log.d("LoginActivity", "登录失败: ${loginResponse?.message}")
                Toast.makeText(this, loginResponse?.message ?: "登录失败", Toast.LENGTH_SHORT).show()
            }
        }

        viewModel.error.observe(this) { error ->
            Log.e("LoginActivity", "发生错误: $error")
            error?.let {
                Toast.makeText(this, "错误: $it", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun initViewModel(): LoginViewModel {
        return ViewModelProvider(this)[LoginViewModel::class.java]
    }
}